import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

const routes = [
 {
  path:'/index',
  name:'index',
  meta:'首页',
  component:()=>import('../views/Index.vue'),
  children:[//二级路由
    {
      path:'/index/home',
      name:'home',
      meta:{title:'主页'},
      component:()=>import('../views/Index/Home.vue')

    },
    {
      path:'/index/tuan',
      name:'tuan',
      meta:'爆爆团',
      component:()=>import('../views/Index/Tuan.vue')
    },
    {
      path:'/index/mine',
      name:'mine',
      meta:{title:'我的'},
      component:()=>import('../views/Index/Mine.vue')
    },
    {
      path:'/index/order',
      name:'order',
      meta:'订单',
      component:()=>import('../views/Index/Order.vue')
    },
    {
      path:'/index',
      redirect:'/index/home'
    },
    {
      path:'*',
      component:()=>import('../views/NotFound.vue')
    }
  ]
},
{
  path:'/detail/:id',
  name:'detail',
  component:()=>import('../views/Detail.vue')
},
{
  path:'/login',
  name:'login',
  meta: {title:{title:'登录'}},
  component:()=>import('../views/Login.vue')
},
{
  path:'/collect',
  name:'collect',
  component:()=>import('../views/Collect.vue')
},
{
  path:'/register',
  name:'register',
  meta:{title:'注册'},
  component:()=>import('../views/Register')
},
{
  path:'/search',
  name:'search',
  meta:'搜索',
  component:()=>import('../views/Search')
},
{
  path:'/address',
  name:'address',
  meta:{title:'地址'},
  component:()=>import('../views/Address')
},
{
  path:'/addaddress',
  name:'addaddress',
  meta:'新增地址',
  component:()=>import('../views/addAddress')
},
{
  path:'/edit',
  name:'edit',
  meta:'编辑地址',
  component:()=>import('../views/edit')
},
{
  path:'/',
  redirect:'/index'
},
{
  path:'*',
  component:()=>import('../views/NotFound.vue')
}
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to,from,next)=>{
  document.title = to.meta.title;
  //获取登录凭证
  var token = localStorage.getItem('token');
  if(to.path == '/index/order'||to.path == '/index/mine'){
    if(token){
      next();//token存在表示已经登录，允许登录
    }else{
      next('/login')
    }
  }else{
    next();
  }
    //对于后台管理系统这种应用, 只有登录页是可以随意访问的, 但是其他所有页面都是必须在登陆以后才可以访问
  // if( to.path == '/register' ){ //跳往 注册页 , 允许跳转
  //   next();
  // }else{
  //   if( to.path == '/login' ){ //跳往 登录页

  //     if( token ){ //已登录 , 重定向到 "/"
  //       next();
  //     }else{ //未登录 , 允许跳往 登录页
  //       next('/login'); 
  //     }
  //     // next();
  //   }else{ //跳往 非登录页
  //     if( token ){ //已登录 , 允许访问
  //       next(); 
  //     }else{ //未登录 , 重定向到 "/login"
  //             next('/login');
  //           }
  //         }
  //       }
})
export default router
